package com.sakila.service.impl;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import com.sakila.dao.MemberDao;
import com.sakila.pojo.Member;
import com.sakila.service.MailService;

@Service
public class MailServiceImpl implements MailService{
//	@Resource
//	private MailSender mailSender;
	@Resource
	private JavaMailSender mailSender;
	@Resource
	private MemberDao memberDao;

	@Override
	public String sendPasswordResetMail(String username) {
		Member member = new Member();
		member.setUsername(username);
		List<Member> list = memberDao.findByProperties(member);
		if(list.size() == 0){
			return null;
		}
		member = list.get(0);
		
		//Reset password to '123'
		BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder(16);
		String newPassword = passwordEncoder.encode(new StringBuilder("123"));
		member.setPassword(newPassword);
		memberDao.updateMember(member);
		
		//String toEmail = getMember.getEmail();
		String toEmail = "sola150@sina.com";
		String fromEmail = "sakila_test@sina.com";
		
		SimpleMailMessage message = new SimpleMailMessage();
		message.setFrom(fromEmail);
		message.setTo(toEmail);
		message.setSubject("Reset Password----Sakila.Net");
		StringBuilder content = new StringBuilder();
		content.append("*Dear " + username + ": \r\n")
 			   .append("*You have successfully reset your password, your new password is: 123 \r\n")
 			   .append("*please login and set a new password asap. \r\n")
 			   .append("*----Sent by Sakila.Net");
		message.setText(content.toString());
		mailSender.send(message);
		return member.getEmail();
	}
}
